package org.exhaust.framework.net.common.protocol.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.exhaust.framework.net.common.protocol.ChannelEventHandler;

@ChannelHandler.Sharable
@Slf4j
public class ConnectionMonitorHandler extends ChannelInboundHandlerAdapter {

    private ChannelEventHandler handler;

    public ConnectionMonitorHandler(ChannelEventHandler handler) {
        this.handler = handler;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channel active:{}", ctx.channel().remoteAddress());
        /**
         * 连接激活时触发登录
         */
        this.handler.channelActive(ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        this.handler.channelInActive(ctx.channel());
        super.channelInactive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        this.handler.channelRegistered(ctx.channel());
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.error("channel unregistered:{}", ctx.channel().remoteAddress());
        this.handler.channelUnRegistered(ctx.channel());
        super.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exception caught:{}", ctx.channel().remoteAddress());
        super.exceptionCaught(ctx, cause);
    }
}
